package cron

import (
	"context"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/transport"
	"github.com/robfig/cron/v3"
	"sync"
)

var (
	_ transport.Server = (*Server)(nil)
)

type ServerOption func(o *Server)

type Server struct {
	*cron.Cron
	sync.RWMutex
	started     bool
	cronOptions []cron.Option
	baseCtx     context.Context

	err error
}

func NewServer(opts ...ServerOption) *Server {
	srv := &Server{
		baseCtx: context.Background(),
		started: false,
	}
	srv.init(opts...)
	srv.Cron = cron.New(srv.cronOptions...)
	return srv
}

func (s *Server) init(opts ...ServerOption) {
	for _, o := range opts {
		o(s)
	}
}

func (s *Server) Name() string {
	return "cron"
}

func (s *Server) Start(ctx context.Context) error {
	if s.err != nil {
		return s.err
	}

	if s.started {
		return nil
	}

	log.Info("[cron] server  加载job数量:", len(s.Cron.Entries()))

	s.Cron.Start()

	s.baseCtx = ctx
	s.started = true

	return nil
}

func (s *Server) Stop(_ context.Context) error {
	log.Info("[cron] server stopping")
	s.started = false
	s.Cron.Stop()
	return nil
}

//func (s *Server) Remove(id cron.EntryID) error {
//	log.Info("[cron] job stopping, job id:", id)
//	s.started = false
//	s.Cron.Remove(id)
//	return nil
//}
